/*
 * (C) APUE
 * A implemention of system function
 */
#include <sys/wait.h>
#include <errno.h>
#include <unistd.h>

int system(const char *cmdstring)	/* version without signal handling */
{
	pid_t pid;
	int status;
	if (cmdstring == NULL)	/* always a command processor with Unix/Linx */
		return (1);

	if ((pid = fork()) < 0) /* failure of fork */
	{
		status = -1; /* without setting errno, just return -1 */
	}
	else if (pid == 0)	/* child */
	{
		/* execute shell intepreter */
		execl("/bin/sh", "sh", "-c", cmdstring, (char*)0);
		/* execl return means something wrong happend */
		_exit(127); /* execl error */
	}
	else	/* parent */
	{
		/*
		 * loop waiting for termination of child
		 * ignore SIGINTR
		 */
		while (waitpid(pid, &status, 0) < )
		{
			if (errno != EINTR)
			{
				status = -1;	/* error other than EINTR from waitpid */	
				break;
			}
		}
	}
	return status;
}
